package one.coder.netty.chapter.fifteen.extend;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel.MapMode;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

/**
 * 大文件传输发送端，用于发送大文件
 * 
 * @author lihzh
 * @alia OneCoder
 * @blog http://www.coderli.com
 */
public class BigFileSendClientHandler extends SimpleChannelHandler {

	// 每次处理的字节数
	private int readLength = 10;
	private ChannelBuffer buffer;

	@Override
	public void channelConnected(ChannelHandlerContext ctx, final ChannelStateEvent e)
			throws Exception {
		// 发送文件
		sendFile(e.getChannel());
	}

	private void sendFile(Channel channel) throws IOException {
		File file = new File("E:/lirgMusic/Eminem-Beautiful.wma");
		long length = file.length();
		long index = 0;
		RandomAccessFile raf = new RandomAccessFile(file, "r");
		while (index < length) {
			int l = (int) (length - index >= readLength ? readLength : length
					- index);
			MappedByteBuffer inputBuffer = raf.getChannel().map(
					MapMode.READ_ONLY, index, l);
			byte[] b = new byte[l];
			inputBuffer.get(b, 0, l);
			sendToServer(b, channel, l);
			index += l;
			System.out.println("Send count: " + index);
		}
		System.out.println("Size: " + index / 1024 / 1024);
	}

	private void sendToServer(byte[] bytes, Channel channel, int length)
			throws IOException {
		if (buffer == null) {
			buffer = ChannelBuffers.buffer(length);
		}
		buffer.writeBytes(bytes);
		ChannelFuture future = channel.write(buffer);
		while (!future.isDone()) {
			System.out.println("dddd");
		}
		buffer.clear();
	}
}
